package com.example.myapplication;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;

public class GameEventDBHelper extends SQLiteOpenHelper {
    // 数据库信息
    private static final String DB_NAME = "game_events.db";
    private static final int DB_VERSION = 2;

    // 表名和列名
    private static final String TABLE_EVENTS = "game_events";
    private static final String COLUMN_ID = "_id";
    private static final String COLUMN_EVENT_ID = "event_id";
    private static final String COLUMN_EVENT_NAME = "event_name";
    private static final String COLUMN_GAME_IP = "game_ip";
    private static final String COLUMN_DATE = "date";
    private static final String COLUMN_LOCATION = "location";
    private static final String COLUMN_DESCRIPTION = "description";
    private static final String COLUMN_PARTICIPANTS = "participants";
    private static final String COLUMN_USER_EMAIL = "user_email";

    // 创建表的SQL语句
    private static final String CREATE_TABLE =
            "CREATE TABLE " + TABLE_EVENTS + " (" +
                    COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    COLUMN_EVENT_ID + " TEXT UNIQUE, " +
                    COLUMN_EVENT_NAME + " TEXT, " +
                    COLUMN_GAME_IP + " TEXT, " +
                    COLUMN_DATE + " TEXT, " +
                    COLUMN_LOCATION + " TEXT, " +
                    COLUMN_DESCRIPTION + " TEXT, " +
                    COLUMN_PARTICIPANTS + " TEXT, " +
                    COLUMN_USER_EMAIL + " TEXT)";

    public GameEventDBHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_EVENTS);
        onCreate(db);
    }

    // 新增活动
    public long addEvent(GameEvent event) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_EVENT_ID, event.getEventId());
        values.put(COLUMN_EVENT_NAME, event.getEventName());
        values.put(COLUMN_GAME_IP, event.getGameIp());
        values.put(COLUMN_DATE, event.getDate());
        values.put(COLUMN_LOCATION, event.getLocation());
        values.put(COLUMN_DESCRIPTION, event.getDescription());
        values.put(COLUMN_PARTICIPANTS, event.getParticipants());
        values.put(COLUMN_USER_EMAIL, event.getUserEmail());
        long id = db.insert(TABLE_EVENTS, null, values);
        db.close();
        return id;
    }

    // 查询当前用户的所有活动（数据隔离核心）
    public List<GameEvent> getEventsByUser(String userEmail) {
        List<GameEvent> events = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(
                TABLE_EVENTS,
                null,
                COLUMN_USER_EMAIL + " = ?",
                new String[]{userEmail},
                null, null, null
        );

        if (cursor != null && cursor.moveToFirst()) {
            do {
                @SuppressLint("Range") GameEvent event = new GameEvent(
                        cursor.getString(cursor.getColumnIndex(COLUMN_EVENT_ID)),
                        cursor.getString(cursor.getColumnIndex(COLUMN_EVENT_NAME)),
                        cursor.getString(cursor.getColumnIndex(COLUMN_GAME_IP)),
                        cursor.getString(cursor.getColumnIndex(COLUMN_DATE)),
                        cursor.getString(cursor.getColumnIndex(COLUMN_LOCATION)),
                        cursor.getString(cursor.getColumnIndex(COLUMN_DESCRIPTION)),
                        cursor.getString(cursor.getColumnIndex(COLUMN_PARTICIPANTS)),
                        cursor.getString(cursor.getColumnIndex(COLUMN_USER_EMAIL))
                );
                events.add(event);
            } while (cursor.moveToNext());
            cursor.close();
        }
        db.close();
        return events;
    }

    // 按条件查询（活动编号、名称）【修正：userEmail从cursor获取】
    public List<GameEvent> queryEvents(String userEmail, String eventId, String eventName) {
        List<GameEvent> events = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        StringBuilder selection = new StringBuilder(COLUMN_USER_EMAIL + " = ?");
        String[] selectionArgs = {userEmail};

        if (eventId != null && !eventId.isEmpty()) {
            selection.append(" AND ").append(COLUMN_EVENT_ID).append(" LIKE ?");
            selectionArgs = new String[]{userEmail, "%" + eventId + "%"};
        }
        if (eventName != null && !eventName.isEmpty()) {
            selection.append(" AND ").append(COLUMN_EVENT_NAME).append(" LIKE ?");
            selectionArgs = new String[]{
                    userEmail,
                    eventId != null ? "%" + eventId + "%" : "%",
                    "%" + eventName + "%"
            };
        }

        Cursor cursor = db.query(
                TABLE_EVENTS,
                null,
                selection.toString(),
                selectionArgs,
                null, null, null
        );

        if (cursor != null && cursor.moveToFirst()) {
            do {
                @SuppressLint("Range") GameEvent event = new GameEvent(
                        cursor.getString(cursor.getColumnIndex(COLUMN_EVENT_ID)),
                        cursor.getString(cursor.getColumnIndex(COLUMN_EVENT_NAME)),
                        cursor.getString(cursor.getColumnIndex(COLUMN_GAME_IP)),
                        cursor.getString(cursor.getColumnIndex(COLUMN_DATE)),
                        cursor.getString(cursor.getColumnIndex(COLUMN_LOCATION)),
                        cursor.getString(cursor.getColumnIndex(COLUMN_DESCRIPTION)),
                        cursor.getString(cursor.getColumnIndex(COLUMN_PARTICIPANTS)),
                        cursor.getString(cursor.getColumnIndex(COLUMN_USER_EMAIL))
                );
                events.add(event);
            } while (cursor.moveToNext());
            cursor.close();
        }
        db.close();
        return events;
    }

    // 修改活动
    public int updateEvent(GameEvent event) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_EVENT_NAME, event.getEventName());
        values.put(COLUMN_GAME_IP, event.getGameIp());
        values.put(COLUMN_DATE, event.getDate());
        values.put(COLUMN_LOCATION, event.getLocation());
        values.put(COLUMN_DESCRIPTION, event.getDescription());
        values.put(COLUMN_PARTICIPANTS, event.getParticipants());
        int rows = db.update(
                TABLE_EVENTS,
                values,
                COLUMN_EVENT_ID + " = ? AND " + COLUMN_USER_EMAIL + " = ?",
                new String[]{event.getEventId(), event.getUserEmail()}
        );
        db.close();
        return rows;
    }

    // 删除活动
    public int deleteEvent(String eventId, String userEmail) {
        SQLiteDatabase db = this.getWritableDatabase();
        int rows = db.delete(
                TABLE_EVENTS,
                COLUMN_EVENT_ID + " = ? AND " + COLUMN_USER_EMAIL + " = ?",
                new String[]{eventId, userEmail}
        );
        db.close();
        return rows;
    }
}